<?php

namespace app\index\controller;

use app\common\controller\Frontend;
use app\index\library\wechat\MiniApp;
use fast\Http;
use think\Cache;
use think\Hook;

class Juliang1 extends Frontend
{
    protected $noNeedLogin = '*';
    protected $noNeedRight = '*';

    public function index()
    {
        $hxq_id = input('hxq_id');
        $hxq = false;
        $id = input('id'); // 商品id
        $goodsModel = model('app\api\model\wanlshop\Goods');
        if ($hxq_id){
            $hxq = db('wanlshop_hxq')->where('id',$hxq_id)->find();
            $sh = $goodsModel
                ->where(['id' => $hxq['goods_id']])->value('sh');
            $id = $hxq_id;
        }else{
            $sh = $goodsModel
                ->where(['id' => $id])->value('sh');
        }
//         = $goods; // 审核
        $event_type = input('event_type'); // 回调id
        $clickid = input('clickid'); // 回调id
        $callback = input('callback'); // 回调id
        $path = input('path'); // 小程序路径
        $bxmid = input('bxm_id');
        $appid = input('appid');
        if ($appid == 'wx496d14ccd8e4ef2d'){
            // 新维度违规替换成品品选购
            $appid = "wxc5e8c1501b7cc695";
        }

        $query = [];
        if ($id){
            $query['id'] = $id;
        }
        if ($clickid){
            $query['clickid'] = $clickid;
        }
        if ($callback){
            $query['cili'] = $callback;
        }
        if ($bxmid){
            $query['bxmid'] = $bxmid;
        }
        if ($event_type){
            $query['event_type'] = $event_type;
        }
        if (!$appid){
            $result = $this->getDomain($path,$query);

            if (!isset($result['url_link'])){
                $key = 'wanlshop_acctocken';
                Cache::store('redis')->rm($key);
                $result = $this->getDomain($path,$query);
            }
        }else{
            $result = $this->getOtherDomain($path,$query,$appid);

            if (!isset($result['url_link'])){
                $key = 'acctocken'.$appid;
                Cache::store('redis')->rm($key);
                $result = $this->getOtherDomain($path,$query,$appid);
            }
        }
        if ($clickid){
            $config = get_addon_config('wanlshop');
            $param = [
                'clickId' => $clickid,
                'eventType' => $event_type,
            ];
            $data = [
                'type' => false,
                'goodsId' => $id,
                'appid' => $appid?:$config['mp_weixin']['appid'],
                'source' => '巨量',
            ];
            Hook::listen('tf_statistics',$param,$data);
        }
        if ($bxmid){
            $config = get_addon_config('wanlshop');
            $param = [
                'clickId' => $bxmid,
                'eventType' => $event_type,
            ];
            $data = [
                'type' => false,
                'goodsId' => $id,
                'appid' => $appid?:$config['mp_weixin']['appid'],
                'source' => '变现猫',
            ];
            Hook::listen('tf_statistics',$param,$data);
        }
        if ($callback){
            $config = get_addon_config('wanlshop');
            $param = [
                'clickId' => $callback,
                'eventType' => $event_type,
            ];
            $data = [
                'type' => false,
                'goodsId' => $id,
                'appid' => $appid?:$config['mp_weixin']['appid'],
                'source' => '磁力',
            ];
            Hook::listen('tf_statistics',$param,$data);
        }

        // $result['url_link'];
//        var_dump($result['url_link']);exit();

        if ($sh){
            $this->redirect($result['url_link']);
        }else{
            if ($hxq_id){
                $id = $hxq['goods_id'];
            }
            // 加载商品模型
            $goodsModel = model('app\api\model\wanlshop\Goods');
            // 查询商品
            $goods = $goodsModel
                ->where(['id' => $id])
                ->field('id,category_id,shop_category_id,brand_id,freight_id,shop_id,title,image,images,flag,content,category_attribute,activity_type,price,sales,payment,comment,praise,moderate,negative,like,views,status')
                ->find();
            if ($goods){
                // 查询类目
                $goods->category->visible(['id','pid','name']);
                // 查询优惠券
                $goods['coupon'] = [];
                // 查询是否关注
                $goods['follow'] = 0;
                // 查询品牌
                $goods->brand->visible(['name']);
                // 查询SKU
                $goods['sku'] = $goods->sku;
                // 查询SPU
                $goods['spu'] = $goods->spu;
                // 查询直播状态
                $goods['isLive'] = model('app\api\model\wanlshop\Live')->where(['shop_id' => $goods['shop_id'], 'state' => 1])->field('id')->find();
                // 查询评论
                $goods['comment_list'] = $goods->comment_list;
                // 获取店铺详情
                $goods->shop->visible(['shopname','service_ids','avatar','city','like','score_describe','score_service','score_logistics']);
                // 查询快递 运费ID 商品重量 邮递城市 商品数量
                $goods['freight'] = [];
                // 查询促销
                $goods['promotion'] = $id; //--下个版本更新--
                // 店铺推荐
                $goods['shop_recommend'] = $goodsModel
                    ->where(['shop_id' => $goods['shop_id'], 'status' => 'normal']) //还可以使用 , 'flag' => 'recommend'
                    ->field('id,title,image,price')
                    ->limit(3)
                    ->select();
                if (!$goods->sku){
                    $goods['market_price'] = $goods['price'];
                    $goods['interval_price'] = $goods['price'];
                }else{
                    $goods['market_price'] = max(array_column($goods->sku,'market_price'));
                    $min = min(array_column($goods->sku,'price'));
                    $max = max(array_column($goods->sku,'price'));
                    $goods['interval_price'] = $min==$max?$min:$min.'-'.$max;
                }
            }

            $this->assign('goods',$goods);

            $this->view->assign('url_link',$result['url_link']??'');
            return $this->view->fetch();
        }
    }

    // 获取小程序跳转域名
    public function getDomain($path,$query = [])
    {
        $config = get_addon_config('wanlshop');
        $appid = $config['mp_weixin']['appid'];
        $secret = $config['mp_weixin']['appsecret'];

        $token = MiniApp::getAccessToken($appid,$secret);
        $query = http_build_query($query);

        $data = [
            "path" => $path,
            "query" => $query,
            "expire_type" => 1,
            "expire_interval" => 1,
        ];

        $options = [
            CURLOPT_HTTPHEADER => array('Content-type: application/json')
        ];

        $result = Http::post("https://api.weixin.qq.com/wxa/generate_urllink?access_token=$token",json_encode($data),$options);

        return json_decode($result,true);

    }

    public function getOtherDomain($path,$query = [],$q_appid)
    {
        $config = get_addon_config('wanlshop');
        $appid = $config['mp_weixin']['appid'];
        $secret = $config['mp_weixin']['appsecret'];

        if ($q_appid && $q_appid != $appid){
            $AppData = MiniApp::getAppInfo($q_appid);
            if ($AppData){
                $appid = $AppData['appid'];
                $secret = $AppData['secret_key'];
            }
        }


        $token = MiniApp::getOtherAccessToken($appid,$secret,'acctocken'.$appid);
        $query = http_build_query($query);

        $data = [
            "path" => $path,
            "query" => $query,
            "expire_type" => 1,
            "expire_interval" => 1,
        ];

        $options = [
            CURLOPT_HTTPHEADER => array('Content-type: application/json')
        ];

        $result = Http::post("https://api.weixin.qq.com/wxa/generate_urllink?access_token=$token",json_encode($data),$options);

        return json_decode($result,true);

    }

    public function wx_qrcode()
    {
        return $this->view->fetch();
    }
}